package com.cat.dataStructure;

/**
 * @author 曲大人的喵
 * @description https://leetcode.cn/problems/minimum-number-of-k-consecutive-bit-flips/
 * @create 2025/8/24 15:34
 * @since JDK17
 */

public class Solution52 {
    public int minKBitFlips(int[] nums, int k) {
        int n = nums.length, ans = 0, sum = 0;
        int[] diff = new int[n + 1];
        for (int i = 0; i < n; i++) {
            sum += diff[i];
            if (nums[i] == sum % 2) {
                diff[i]++;
                diff[i + k]--;
                sum++;
                ans++;
            }
            if (sum > 0) {  // 需要反转
                if (sum % 2 != 0) { // 还得翻
                    nums[i] = 1 - nums[i];
                }
            }
        }
        for (int num : nums) {
            if (num != 1) {
                return -1;
            }
        }

        return ans;
    }
}
